package com.lxf.clouduser.service.impl;

import com.lxf.clouduser.bean.*;
import com.lxf.clouduser.mapper.*;
import com.lxf.clouduser.netty.LocalData;
import com.lxf.clouduser.service.ChatService;
import com.lxf.clouduser.utils.AudioMsgUtils;
import com.lxf.clouduser.utils.SnowflakeIdGenerator;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.sound.sampled.AudioFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author 罗兴发
 * @data 2025/6/13 10:31
 * @description：聊天-业务实现层
 */
@Service
@Slf4j
public class ChatServiceImpl implements ChatService {
    private String GroupHeadPic = "http://pic.imeitou.com/uploads/allimg/181027/3-1Q02GK159.jpg";
    @Resource
    GroupMapper groupMapper;
    @Resource
    UserMsgMapper userMsgMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    private UserItemRepository userItemRepository;
    @Resource
    private UserMsgItemRepository userMsgItemRepository;
    @Resource
    private GroupItemRepository groupItemRepository;
    @Resource
    private AudioMsgUtils audioMsgUtils;

    /**
     * 在线聊天
     * @param reqModel
     * @param respModel
     */
    @Override
    public void addUser(ReqModel reqModel, RespModel respModel) {
        //请求格式：{"uid":"1","type":1,"nickname":"张三","bridge":[],"groupId":""}
        String uid = reqModel.getUid();
        String nickname = reqModel.getNickname();
        respModel.setMsg(nickname+ " : 加入聊天室");
        UserBean userModel = new UserBean();
        userModel.setUserId(Integer.valueOf(uid));
        userModel.setUserName(nickname);
        userModel.setIsOnline(1);
        //个人在线设置
        LocalData.userlist.add(userModel);
        //将用户状态更改为在线
        userMapper.updateUserStatusByUserId(Integer.valueOf(uid),1);
        //群聊在线设置，查询用户加入的群聊
        List<UserGroupBean> list = groupMapper.getGroupByGroupUserId(uid);
        if (list.size()>0){
            for (UserGroupBean groups:list) {//查找该用户所加入的群信息
                //群ID
                String groupId = groups.getGroupId();
                GroupBean group = groupMapper.getGroupByGroupId(groupId);
                //遍历群列表
                for (GroupBean temp:LocalData.grouplist) {
                    if (groupId.equals(temp.getGroupId())) {
                        LocalData.grouplist.remove(temp);
                        respModel.setGroups(LocalData.grouplist);
                        break;
                    }
                }

                //根据群ID查询该群下面的在线群成员信息
                List<UserBean> users = userMapper.getGroupAllUserByGroupId(groupId,1);
                group.setUsers(users);
                if(!LocalData.grouplist.contains(group)){
                    //加入到数组中
                    LocalData.grouplist.add(group);
                }
            }
        }

        respModel.setUsers(LocalData.userlist);
        respModel.setGroups(LocalData.grouplist);
    }

    /**
     * 断线
     * @param reqModel
     * @param respModel
     */
    @Override
    public void delUser(ReqModel reqModel, RespModel respModel) {
        //请求格式：{"uid":"1","type":2,"nickname":"张三","bridge":[],"groupId":""}
        String uid = reqModel.getUid();
        String nickname = reqModel.getNickname();
        respModel.setMsg(nickname + " : 离开聊天室");
        UserBean userModel = null;
        //遍历在线用户的列表
        for (int i = 0; i < LocalData.userlist.size(); i++) {
            UserBean temp = LocalData.userlist.get(i);
            if (String.valueOf(temp.getUserId()).equals(reqModel.getUid())) {
                userModel = temp;
                break;
            }
        }
        //将用户状态更改为离线
        userMapper.updateUserStatusByUserId(Integer.valueOf(uid),0);
        log.info("列表："+LocalData.userlist);
        log.info("需要删除的用户："+userModel);
        //在用户列表删除要下线的用户
        LocalData.userlist.remove(userModel);
        //群聊在线设置
        List<UserGroupBean> list = groupMapper.getGroupByGroupUserId(uid);
        if (list.size()>0){
            for (UserGroupBean groups:list) {//查找该用户所加入的群信息
                //群ID
                String groupId = groups.getGroupId();
                GroupBean group = groupMapper.getGroupByGroupId(groupId);
                //遍历群列表
                for (GroupBean temp:LocalData.grouplist) {
                    if (groupId.equals(temp.getGroupId())) {
                        LocalData.grouplist.remove(temp);
                        respModel.setGroups(LocalData.grouplist);
                        break;
                    }
                }

                //根据群ID查询该群下面的在线群成员信息
                List<UserBean> users = userMapper.getGroupAllUserByGroupId(groupId,1);
                group.setUsers(users);
                if(!LocalData.grouplist.contains(group)){
                    //加入到数组中
                    LocalData.grouplist.add(group);
                }
            }
        }
        respModel.setUsers(LocalData.userlist);
        respModel.setGroups(LocalData.grouplist);
    }

    /**
     * 创建群聊
     * @param reqModel
     * @param respModel
     */
    @Override
    @Transactional(rollbackFor = Exception.class)//开启事务
    public void addGroup(ReqModel reqModel, RespModel respModel) {
        // 请求格式：{"uid":"1","type":10,"nickname":"张三","groupName":"测试","bridge":[]}
        //获取参数
        String uid = reqModel.getUid();
        String nickname = reqModel.getNickname();
        String groupName = reqModel.getGroupName();
        String groupHead = reqModel.getGroupHead();
        respModel.setMsg(nickname + ":创建了群 ：" + groupName);
        //    把创建者加入到群组的成员列表中
        UserBean userModel = new UserBean();
        userModel.setUserId(Integer.valueOf(uid));
        userModel.setUserName(nickname);
        List<UserBean> users = new ArrayList<>();
        users.add(userModel);
        //群号，由系统自动生成
        SnowflakeIdGenerator snowflakeIdGenerator = new SnowflakeIdGenerator(1,1);
        String groupId = snowflakeIdGenerator.getGroupId();
        log.info("群号为：{}",groupId);
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String addTime = sf.format(new Date());
        //还需要到
        GroupBean groupModel = new GroupBean();
        groupModel.setGroupId(groupId);
        groupModel.setGroupName(groupName);

        if (null==groupHead||"".equals(groupHead)){
            groupModel.setGroupHead(GroupHeadPic);
        }else {
            groupModel.setGroupHead(groupHead);
        }
        MsgType type = MsgType.getTypeByNum(4);
        groupModel.setGroupNotice(type.getDesc());
        groupModel.setUsers(users);
        groupModel.setAddTime(addTime);
        LocalData.grouplist.add(groupModel);
        respModel.setGroups(LocalData.grouplist);
        //添加到数据库
        List<GroupBean> list = new ArrayList<>();
        list.add(groupModel);
        //打印
        log.info("list集合："+list);
        int i = groupMapper.addGroup(list);
        if (i<0)log.info("添加失败");
        else {
            log.info("添加成功");
            //添加es
            groupItemRepository.save(groupModel);
            //将创建者加入群聊中
            UserGroupBean ug = new UserGroupBean();
            ug.setGroupId(groupId);
            ug.setUserId(Integer.valueOf(uid));
            ug.setUserRole(2);
            ug.setAddTime(addTime);
            //list封装
            List<UserGroupBean> list1 = new ArrayList<>();
            list1.add(ug);
            //添加群主
            int i1 = groupMapper.addGroupUser(list1);
            if (i1<0)log.info("群主添加失败");
            else log.info("群主添加成功");
            //发送消息，请求体
            ReqModel r = new ReqModel();
            r.setUid(uid);
            r.setType(100);
            r.setNickname(reqModel.getNickname());
            List<String> list2 = new ArrayList<>();
            list2.add("");
            list2.add(uid);
            r.setBridge(list2);
            String msg = "您已成功创建了群 ：【" + groupName + "】,群号为：【" + groupId + "】";
            r.setMsg(msg);
            //发送消息
            sendPrivateMsg(r,respModel);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)//开启事务
    public void delGroup(ReqModel reqModel, RespModel respModel) {
        // 请求格式：{"uid":"1","type":40,"nickname":"张三","groupName":"测试","groupId":"123456789","bridge":[]}
        //获取参数
        String uid = reqModel.getUid();
        String nickname = reqModel.getNickname();
        String groupName = reqModel.getGroupName();
        String groupId = reqModel.getGroupId();
        respModel.setMsg(nickname + ":删除了群 ：" + groupName);
        //还需要到
        GroupBean groupModel = new GroupBean();
        groupModel.setGroupId(groupId);
        groupModel.setGroupName(groupName);
        LocalData.grouplist.remove(groupModel);
        respModel.setGroups(LocalData.grouplist);
        //删除操作
        int i = groupMapper.delGroup(groupId);
        if (i<0)log.info("删除失败");
        else {
            log.info("删除成功");
            //删除es
            groupItemRepository.deleteById(groupId);
            //删除所有群成员信息
            int i1 = groupMapper.delGroupUser(groupId,null);
            if (i1<0)log.info("删除群成员失败");
            else log.info("删除群成员成功");
            //发送消息，请求体
            ReqModel r = new ReqModel();
            r.setUid(uid);
            r.setType(100);
            r.setNickname(nickname);
            List<String> list2 = new ArrayList<>();
            list2.add("");
            list2.add(uid);
            r.setBridge(list2);
            String msg = "您已成功解散了群 ：【" + groupName + "】,群号为：【" + groupId + "】";
            r.setMsg(msg);
            //发送消息
            sendPrivateMsg(r,respModel);
        }
    }

    /**
     * 加入群聊
     * @param reqModel
     * @param respModel
     */
    @Override
    @Transactional(rollbackFor = Exception.class)//开启事务
    public void joinGroup(ReqModel reqModel, RespModel respModel) {
        //请求格式：{"uid":"1","type":20,"nickname":"张三","groupName":"测试","bridge":[],"groupId":"123456789"}
        String nickname = reqModel.getNickname();
        String groupName = reqModel.getGroupName();
        String groupId = reqModel.getGroupId();
        String uid = reqModel.getUid();
        //消息响应
        respModel.setMsg(nickname + ":加入了群 ：" + groupName);
        Integer userId = Integer.valueOf(uid);
        for (GroupBean groupModel : LocalData.grouplist) {
            if (groupModel.getGroupId().equals(groupId)) {
                UserBean userModel = new UserBean();
                userModel.setUserId(userId);
                userModel.setUserName(reqModel.getNickname());
                groupModel.getUsers().add(userModel);
            }
        }
        respModel.setGroups(LocalData.grouplist);
        //需要查询用户是否是上线还是新加入群聊信息
        UserGroupBean userGroupBean = groupMapper.getGroupUserByGroupId(groupId,userId);
        //若是新加入群聊的用户，则无需加入到数据库
        if (null==userGroupBean){
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String addTime = sf.format(new Date());
            UserGroupBean ug = new UserGroupBean();;
            ug.setUserRole(0);
            ug.setGroupId(groupId);
            ug.setUserId(userId);
            ug.setAddTime(addTime);
            //list封装
            List<UserGroupBean> list = new ArrayList<>();
            list.add(ug);
            //添加群成员
            int i = groupMapper.addGroupUser(list);
            if (i<0)log.info("加入群失败");
            else {
                log.info("加入群成功");
                //发送消息，请求体
                ReqModel r = new ReqModel();
                r.setUid(uid);
                r.setType(100);
                r.setNickname(reqModel.getNickname());
                //Bridge值设置
                List<String> list2 = new ArrayList<>();
                list2.add("");
                list2.add(uid);
                r.setBridge(list2);
                String msg = "您已加入群 ：【" + groupName + "】,群号为：【" + groupId + "】";
                r.setMsg(msg);
                //发送消息
                sendPrivateMsg(r,respModel);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)//开启事务
    public void leaveGroup(ReqModel reqModel, RespModel respModel) {
        //请求格式：{"uid":"1","type":40,"nickname":"张三","groupName":"测试","bridge":[],"groupId":"123456789"}
        String nickname = reqModel.getNickname();
        String groupName = reqModel.getGroupName();
        String groupId = reqModel.getGroupId();
        String uid = reqModel.getUid();
        respModel.setMsg(nickname + ":退出了群 ：" + groupName);
        Integer userId = Integer.valueOf(uid);
        //循环查询
        for (GroupBean groupModel : LocalData.grouplist) {
            if (groupModel.getGroupId().equals(groupId)) {
                UserBean userModel = new UserBean();
                userModel.setUserId(userId);
                userModel.setUserName(nickname);
                groupModel.getUsers().remove(userModel);
            }
        }
        respModel.setGroups(LocalData.grouplist);

        //删除用户群组中间表
        groupMapper.delGroupUser(groupId,userId);

        //发送消息，请求体
        ReqModel r = new ReqModel();
        r.setUid(uid);
        r.setType(100);
        r.setNickname(nickname);
        //Bridge值设置
        List<String> list2 = new ArrayList<>();
        list2.add("");
        list2.add(uid);
        r.setBridge(list2);
        String msg = "您已退出群 ：【" + groupName + "】,群号为：【" + groupId + "】";
        r.setMsg(msg);
        //发送消息
        sendPrivateMsg(r,respModel);
    }

    /**
     * 发送群聊信息
     * @param reqModel
     * @param respModel
     */
    @Override
    public void sendGroupMsg(ReqModel reqModel, RespModel respModel) {
        //请求格式：{"uid":"1","type":100 ,"nickname":"张三","bridge":[],"groupId":"21312312","groupName": "测试群聊","msg":"大家好啊我是张三"}
        log.info("发送群消息");
        String uid = reqModel.getUid();
        String msg = reqModel.getMsg();
        Integer msgType = reqModel.getMsgType();
        String groupId = reqModel.getGroupId();
        List<String> bridge = reqModel.getBridge();
        //时间规格化
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String addTime = sf.format(new Date());
        //list集合
        List<UserMsgBean> list = new ArrayList<>();
        //查询该群成员列表
        List<UserBean> l = userMapper.getGroupAllUserByGroupId(groupId, null);
        for (UserBean user:l) {
            String userId = String.valueOf(user.getUserId());
            //给群里面每一个成员发一条消息，
            // 因为要标识未读或者已读，所以需要给每一位成员发消息
            //对象实例化
            UserMsgBean userMsg = new UserMsgBean();
            userMsg.setMsgContent(msg);
            userMsg.setFromUserId(uid);
            //查询用户信息1
            Optional<UserBean> u = userItemRepository.findById(uid);
            if (u.isPresent()){
                UserBean u1 = u.get();
                userMsg.setFromUserName(u1.getUserName());
                userMsg.setFromUserHead(u1.getUserHead());
            }
            userMsg.setToUserId(userId);
            //查询用户信息2
            Optional<UserBean> u2 = userItemRepository.findById(userId);
            if (u2.isPresent()){
                UserBean u3 = u2.get();
                userMsg.setToUserName(u3.getUserName());
                userMsg.setToUserHead(u3.getUserHead());
            }
            userMsg.setGroupId(groupId);
            userMsg.setMsgType(msgType);
            userMsg.setAddTime(addTime);
            list.add(userMsg);

            //es添加消息
            userMsgItemRepository.save(userMsg);
        }
        //添加消息
        userMsgMapper.addUserMsg(list);
        for (UserMsgBean m:list) {
            //消息响应
            respModel.setMsgId(m.getUmId());
            respModel.setUid(uid);
            respModel.setMsg(msg);
            respModel.setGroupId(groupId);
            respModel.setBridge(bridge);
            respModel.setMsgType(msgType);
            respModel.setIsOnline(1);
        }

    }

    /**
     * 发送一对一信息
     * @param reqModel
     * @param respModel
     */
    @Override
    public void sendPrivateMsg(ReqModel reqModel, RespModel respModel) {

        //请求格式：{"uid":"1","type":100 ,"nickname":"张三","bridge":["1","2"],"groupId":"","msg":"你好啊李四同学"}
        log.info("发送一对一消息");
        String uid = reqModel.getUid();
        String msg = reqModel.getMsg();
        List<String> bridge = reqModel.getBridge();

        //时间规格化
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String addTime = sf.format(new Date());

        //list集合
        List<UserMsgBean> list = new ArrayList<>();
        String toUserId = bridge.get(1);

        //对象实例化
        UserMsgBean userMsg = new UserMsgBean();
        userMsg.setMsgContent(msg);
        userMsg.setFromUserId(uid);
        //查询用户信息1
        Optional<UserBean> u = userItemRepository.findById(uid);
        if (u.isPresent()){
            UserBean u1 = u.get();
            userMsg.setFromUserName(u1.getUserName());
            userMsg.setFromUserHead(u1.getUserHead());
        }
        userMsg.setToUserId(toUserId);
        //查询用户信息2
        Optional<UserBean> u2 = userItemRepository.findById(toUserId);
        if (u2.isPresent()){
            UserBean u3 = u2.get();
            userMsg.setToUserName(u3.getUserName());
            userMsg.setToUserHead(u3.getUserHead());
        }
        userMsg.setMsgType(3);
        userMsg.setGroupId("");
        userMsg.setAddTime(addTime);
        list.add(userMsg);

        //添加消息
        userMsgMapper.addUserMsg(list);

        //es添加消息
        userMsgItemRepository.save(userMsg);

        //消息响应
        respModel.setMsgId(userMsg.getUmId());
        respModel.setMsg(msg);
        respModel.setGroupId("");
        respModel.setIsOnline(1);
        respModel.setMsgType(3);
    }

    @Override
    public void audioMsg(ReqModel reqModel, RespModel respModel) {
        List<String> bridge = reqModel.getBridge();
        String s = bridge.get(1);
        Channel channel = LocalData.channelUserUrl.get(s);
        if (null==channel){
            log.info("该用户不在线，请稍后重试");
        }else {
            log.info("进入语音通话");
            audioMsgUtils.initializeAudio();
            audioMsgUtils.startStreaming();
        }
    }
}
